# -*- encoding: utf-8 -*-
import base64
import copy
import datetime
import io

import xlwt

from odoo import models
from odoo.exceptions import UserError


class StatementCurrentAccountsInherit(models.Model):
    _inherit = ['statement.current.accounts']

    # 返回header
    def _sheet_header(self):
        header_list = [
            [self._description],
            ['日期', '凭证号', '原单据', '摘要', '借贷', '借方金额', '贷方金额', '期末']
        ]
        return header_list

    # 返回data
    def _sheet_content(self):
        content_list = []
        lines = self.line_ids
        if not lines:
            raise UserError('明细行不能为空')
        for line in lines:
            content_list.append([
                line.date and line.date.strftime('%Y-%m-%d') or datetime.now().strftime('%Y-%m-%d'),
                line.name,
                line.origin,
                line.remark,
                line.dc_type,
                line.debit,
                line.credit,
                line.balance,
            ])
        return content_list

    def export_file(self):
        result = self._sheet_header() + self._sheet_content()
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet(self._description, cell_overwrite_ok=True)
        # 居中
        alignment = xlwt.Alignment()
        alignment.horz = 0x02
        alignment.vert = 0x01
        # 外边框
        borders = xlwt.Borders()
        borders.left = 1
        borders.right = 1
        borders.top = 1
        borders.bottom = 1
        borders.bottom_colour = 0x3A
        # 字体
        font = xlwt.Font()
        font.name = '微软雅黑'
        font.height = 11 * 20
        head_font = copy.copy(font)
        head_font.bold = True
        style = xlwt.XFStyle()
        style.alignment = alignment
        style.borders = borders
        style.font = font
        head_style = copy.copy(style)
        head_style.font = head_font

        for i in range(len(result)):
            for j in range(len(result[i])):
                if i == 0:
                    last_col = len(result[i + 1]) - 1
                    sheet.write_merge(r1=0, r2=0, c1=0, c2=last_col, label=result[i][j], style=head_style)
                else:
                    sheet.write(i, j, result[i][j], style)
        fp = io.BytesIO()
        wbk.save(fp)
        fp.seek(0)
        data = fp.read()
        fp.close()

        file_name = "%s-%s %s.xls" % (str(self.start_date), str(self.end_date), self._description)
        obj = self.env['wizard.account.designer.excel.report'].create(
            {'name': True, 'report': base64.b64encode(data), 'file_name': file_name})
        # return data
        return {
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'res_model': 'wizard.account.designer.excel.report',
            'target': 'new',
            'res_id': obj.id,
        }
